package dbopr

import (
	"fmt"
	"github.com/pkg/errors"
	"myCloud/dbmodel"
	"strconv"
)

type userProvider struct{}

func NewUserProvider() *userProvider {
	return &userProvider{}
}

func (m *userProvider) New(user *dbmodel.User) error {
	return dbSession.Create(user).Error
}

func (m *userProvider) CheckUserToken(userId, token string) (*dbmodel.User, *dbmodel.UserToken, error) {
	uID, err := strconv.Atoi(userId)
	if err != nil {
		return nil, nil, errors.Wrap(err, "userID format error")
	}

	tokenProvider := NewUserTokenProvider()
	tokenPtr, notFound, err := tokenProvider.Get(token)
	if notFound {
		err = fmt.Errorf("cannot found token from db")
		return nil, nil, err
	}
	if err != nil {
		return nil, nil, errors.Wrap(err, "get token failed.")
	}

	u, notFound, err := m.QueryById(tokenPtr.UserID)
	if err != nil {
		return nil, nil, errors.Wrap(err, "query user by id failed.")
	}
	if notFound {
		return nil, nil, errors.New("cannot found special user")
	}
	if int(u.ID) != uID {
		return nil, nil, errors.New("user information not match")
	}

	return u, tokenPtr, nil
}

func (m *userProvider) CheckUserPassword(userName, password string) (*dbmodel.User, error) {
	var out dbmodel.User
	query := dbSession.Where("user_name=? and stat='VALID'", userName).First(&out)
	if query.RecordNotFound() {
		return nil, errors.New("cannot found user")
	}

	// 故意与上面返回相同
	if !out.CheckPwd(password) {
		return nil, errors.New("cannot found user")
	}

	return &out, nil
}

func (m *userProvider) QueryById(userId uint) (*dbmodel.User, bool, error) {
	var out dbmodel.User
	query := dbSession.Where("id=? and stat='VALID'", userId).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}

	return &out, false, query.Error
}
